package org.wx.io.netty.codec2;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @description: proto client handler
 * @author: wangxun
 * @createDate: 2021/2/19
 * @version: 1.0
 */
@Slf4j
public class ProtoClientHandler extends SimpleChannelInboundHandler<MyDataInfo.MyInfo> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyInfo msg) throws Exception {
        MyDataInfo.MyInfo.DataType dataType = msg.getDataType();
        switch (dataType){
            case SType:
                MyDataInfo.Student student = msg.getStudent();
                log.info("发送过来的是学生数据 学生ID:{} 学生名字:{}",student.getId(),student.getName());
                echo(ctx);
                break;
            case TType:
                MyDataInfo.Teacher teacher = msg.getTeacher();
                log.info("发送过来的是教师数据 教师工作ID:{} 教师名字:{}",teacher.getWorkId(),teacher.getName());
                echo(ctx);
                break;
        }
    }

    private void echo(ChannelHandlerContext ctx) {

        int i = new Random().nextInt(3);
        MyDataInfo.MyInfo info = null;
        if(i<2){
            info  = MyDataInfo.MyInfo.newBuilder().setDataType(MyDataInfo.MyInfo.DataType.SType)
                    .setStudent(MyDataInfo.Student.newBuilder().setId(8888).setName("服务器：哈哈" + i).build()).build();
        }else{
            info = MyDataInfo.MyInfo.newBuilder().setDataType(MyDataInfo.MyInfo.DataType.TType)
                    .setTeacher(MyDataInfo.Teacher.newBuilder().setWorkId(3333).setName("服务器：呵呵"+i).build()).build();
        }

        ctx.writeAndFlush(info);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        int i = new Random().nextInt(3);
        MyDataInfo.MyInfo info = null;
        if(i<2){
            info  = MyDataInfo.MyInfo.newBuilder().setDataType(MyDataInfo.MyInfo.DataType.SType)
                    .setStudent(MyDataInfo.Student.newBuilder().setId(1001).setName("哈哈" + i).build()).build();
        }else{
            info = MyDataInfo.MyInfo.newBuilder().setDataType(MyDataInfo.MyInfo.DataType.TType)
                    .setTeacher(MyDataInfo.Teacher.newBuilder().setWorkId(9999).setName("呵呵"+i).build()).build();
        }

        ctx.writeAndFlush(info);
    }
}
